package com.example.siyun.config;

import com.example.siyun.handle.CustomAuthenticationFailureHandler;
import com.example.siyun.handle.CustomAuthenticationSuccessHandler;
import com.example.siyun.security.SmsAuthenticationFilter;
import com.example.siyun.service.impl.loginserviceimpl.SmsAuthenticationProvider;
import com.example.siyun.service.impl.loginserviceimpl.SmsUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @Auther: 全
 * @Date: 2022/10/13 09:05
 * @Description:
 */
@Configuration
public class SmsSecurityConfigurerAdapter extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Autowired
    CustomAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    CustomAuthenticationFailureHandler authenticationFailureHandler;


    @Resource
    private SmsUserDetailsService smsUserDetailsService;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //设置身份验证成功处理程序
        smsAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        //设置身份验证失败处理程序
        smsAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider(smsUserDetailsService,redisTemplate);
        http.authenticationProvider(smsAuthenticationProvider)
                .addFilterAfter(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
